from fastapi import APIRouter,Depends,Request,HTTPException, status
from pydantic import BaseModel
from jose import JWTError, jwt
from datetime import timedelta

from app.config.database import connect
from app.api.auth import create_access_token, get_user,ACCESS_TOKEN_EXPIRE_MINUTES
from app.models.models import User,UserCat

from app.common.common import returnData
import json

router = APIRouter()

class UserInDB(BaseModel):
    openid: str
    nickname: str
                                   
@router.post("/login/", response_model=dict)
async def login_for_access_token(request: Request):
    
    try:
        data = await request.json()
    except json.JSONDecodeError:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid JSON body")
    
    openid = data.get('openid')
    nickname = data.get('nickname')
    
    if not openid:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Missing openid")
        
    user = User.objects(openid=openid).first()
    if not user:
        # 如果用户不存在，则创建用户
        user = User(openid=openid, nickname=nickname, level=1).save()
        user = User.objects(openid=user_data.openid).first()
        # print(user)
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(data={"sub": user.openid})
    
    return returnData(200, '登录成功', {"access_token": access_token, "token_type": "bearer","user":user.get_user_info()})
    return {"access_token": access_token, "token_type": "bearer"}



# @router.route('/sgin', methods=["GET","POST"])
# def login(request):
#     code, msg, json = service.login(request)
#     return returnData(code, msg, json)




# 其他路由...

# 你可以在其他路由中使用`get_user`函数来验证JWT
# 例如：
@router.get("/get_user/", dependencies=[Depends(get_user)])
async def read_items(user: User = Depends(get_user)):
    if user:
        return returnData(200, '查询成功', user.get_user_info())
    else:
        return returnData(401, 'Unauthorized', None)
        
    # return returnData(200, '查询成功', user.get_user_info())
    # # return [{"item_id": "Foo", "owner": user.nickname}]
    
@router.get("/get_user_cat/", dependencies=[Depends(get_user)])
async def get_user_cat(user: User = Depends(get_user)):\
    print(user.openid)
    
    
    
# # 更新用户信息
# @router.put("/users/{user_id}")
# async def update_user(user_id: str, user_data: UserInDB, user: User = Depends(get_user)):
#     user_to_update = User.objects(id=ObjectId(user_id)).first()
#     if not user_to_update:
#         raise HTTPException(status_code=404, detail="User not found")
#     user_to_update.nickname = user_data.nickname
#     user_to_update.level = user_data.level
#     user_to_update.save()
#     return {"id": str(user_to_update.id), "nickname": user_to_update.nickname, "level": user_to_update.level}    
    
# # 删除用户
# @router.delete("/users/{user_id}")
# async def delete_user(user_id: str, user: User = Depends(get_user)):
#     user_to_delete = User.objects(id=ObjectId(user_id)).first()
#     if not user_to_delete:
#         raise HTTPException(status_code=404, detail="User not found")
#     user_to_delete.delete()
#     return {"message": "User deleted"}